<template>
  <div class="">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-button type="primary" @click="addDiglogVisable = true">添加角色</el-button>

      <el-table :data="roles" border stripe="">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item, i1) in scope.row.children" :key="item.id">
              <!-- 渲染一级等级 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightsById(scope.row, item.id)">{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级等级 和 三级等级 -->
              <el-col :span="19">
                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, i2) in item.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightsById(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightsById(scope.row, item3.id)">
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editDiglogInit(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRoleById(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightsDiglog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分配权限对话框 -->
      <el-dialog title="分配权限" :visible.sync="setRightsDiglogVisiable" width="50%" @close="setRightsDiglogClose">
        <!-- Tree 树形控件 -->
        <el-tree :data="rights" show-checkbox node-key="id" :default-expanded-keys="defKeys" :default-checked-keys="defKeys" :props="treeProps" ref="treeRef"> </el-tree>

        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightsDiglogVisiable = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 添加角色对话框 -->
      <el-dialog title="添加角色" :visible.sync="addDiglogVisable" width="50%" @close="diglogClose('add')">
        <!-- 内容主体区域 -->
        <el-form :model="addForm" :rules="formRules" ref="addFormRef" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDiglogVisable = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑角色的对话框 -->
      <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%" @close="diglogClose('edit')">
        <!-- 编辑角色信息的表单 -->
        <el-form :model="editForm" :rules="formRules" ref="editFormRef" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roles: [],
      setRightsDiglogVisiable: false,
      rights: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defKeys: [],
      roleId: '',
      addDiglogVisable: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      editForm: {},
      editDialogVisible: false,
      formRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },

  created() {
    this.getRoles()
  },

  methods: {
    async getRoles() {
      const { data: resp } = await this.$http.get('roles')
      if (resp.meta.status != 200 && resp.meta.status != 201) {
        return this.$message.error(resp.meta.msg)
      }
      this.roles = resp.data
    },

    async removeRightsById(role, rightsId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: resp } = await this.$http.delete(`roles/${role.id}/rights/${rightsId}`)
      if (resp.meta.status !== 200) {
        return this.$message.error(resp.meta.msg)
      }
      this.$message.success('删除权限成功')

      const { data: resp2 } = await this.$http.get(`roles/${role.id}/rights`)
      if (resp.meta.status == 200) {
        //   this.getUserList()
        role.children = resp2.data.children
      }
    },

    async showSetRightsDiglog(role) {
      const { data: resp } = await this.$http.get(`rights/tree`)
      if (resp.meta.status !== 200) {
        return this.$message.error(resp.meta.msg)
      }
      this.rights = resp.data
      this.roleId = role.id
      this.getLeafrights(role, this.defKeys)
      this.setRightsDiglogVisiable = true
    },

    setRightsDiglogClose() {
      this.defKeys = []
    },

    async allotRights() {
      const kesy = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]

      const { data: resp } = await this.$http.put(`roles/${this.roleId}/rights`, {
        rids: kesy.join(',')
      })
      if (resp.meta.status !== 200) {
        return this.$message.error(resp.meta.msg)
      }
      this.$message.success('分配权限成功')
      this.setRightsDiglogVisiable = false
      this.getRoles()
    },

    getLeafrights(node, arr) {
      if (!node.children) {
        arr.push(node.id)
      } else {
        node.children.forEach(element => {
          this.getLeafrights(element, arr)
        })
      }
    },

    //监听对话框关闭事件
    diglogClose(operation) {
      if (operation === 'add') {
        this.$refs.addFormRef.resetFields()
      } else if (operation === 'edit') {
        this.$refs.editFormRef.resetFields()
      }
    },

    // 添加角色
    addRole() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: resp } = await this.$http.post('roles', this.addForm)
        if (resp.meta.status !== 200 && resp.meta.status !== 201) {
          return this.$message.error(resp.meta.msg)
        }
        this.$refs.addFormRef.resetFields()
        this.addDiglogVisable = false
        this.$message.success('添加角色成功')
        this.getRoles()
      })
    },
    editDiglogInit(roleInfo) {
      this.editForm = JSON.parse(JSON.stringify(roleInfo))
      this.editDialogVisible = true
    },
    editRoleInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: resp } = await this.$http.put(`roles/${this.editForm.id}`, {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc
        })

        if (resp.meta.status !== 200) {
          return this.$message.error(resp.meta.msg)
        }
        this.$refs.editFormRef.resetFields()
        this.editDialogVisible = false
        this.$message.success('修改角色成功')
        this.getRoles()
      })
    },

    async deleteRoleById(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: resp } = await this.$http.delete(`roles/${id}`)
      if (resp.meta.status !== 200) {
        return this.$message.error(resp.meta.msg)
      }
      this.$message.success('删除角色成功')
      this.getRoles()
    },
  }
}
</script>
<style scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 2px solid #eee;
}
.bdbottom {
  border-bottom: 2px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>